<template>
  <div class="energy-share-container" tabindex="0" @keydown.delete="handleDeleteLastToken">
    <div class="header">
      <h2>段计算规则设置</h2>
      <el-button type="primary" @click="addSection">添加段</el-button>
    </div>

    <div class="sections-container">
      <div 
        v-for="(section, index) in sections" 
        :key="section.id" 
        class="section-card"
      >
        <div class="section-header">
          <div class="section-title">
            <el-input 
              v-if="section.editingName" 
              v-model="section.name" 
              size="small"
              @blur="section.editingName = false"
              @keyup.enter="section.editingName = false"
            ></el-input>
            <span v-else @click="editSectionName(index)">section {{index + 1}} {{ section.name !== null && section.name !== '' ? `(${section.name})` : '' }}</span>
          </div>
          <div class="section-actions">
            <el-button 
              type="text" 
              size="small" 
              @click="section.editingName = true"
            >
              <i class="el-icon-edit"></i>
            </el-button>
            <el-button 
              v-if="!section.editingRule"
              type="text" 
              size="small" 
              @click="editRule(index)"
            >
              <i class="el-icon-setting"></i> 编辑规则
            </el-button>
            <el-button 
              v-else
              type="text" 
              size="small" 
              @click="cancelEditRule(index)"
            >
              <i class="el-icon-close"></i> 取消编辑
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="deleteSection(index)"
            >
              <i class="el-icon-delete"></i>
            </el-button>
          </div>
        </div>

        <div class="section-content">
          <!-- 预览模式 -->
          <div v-if="!section.editingRule" class="preview-mode">
            <div class="expression-preview">
              <!--<div class="preview-label">表达式:</div>-->
              <div class="expression-content">
                <template v-if="section.calculation.expressionTokens.length > 0">
                  <template v-for="(token, tIndex) in section.calculation.expressionTokens">
                    <span 
                      v-if="token.type === 'point'" 
                      :key="tIndex"
                      class="token point-link"
                      @click="showPointInfo(token.value)"
                    >
                      {{ getPointNameById(token.value) }}
                    </span>
                    <span 
                      v-else-if="token.type === 'operator'" 
                      :key="tIndex"
                      class="token operator-text"
                    >
                      {{ token.value }}
                    </span>
                    <span 
                      v-else-if="token.type === 'number'" 
                      :key="tIndex"
                      class="token number-text"
                    >
                      {{ token.value }}
                    </span>
                    <span 
                      v-else 
                      :key="tIndex"
                      class="token"
                    >
                      {{ token.value }}
                    </span>
                    <span :key="'space-'+tIndex" v-if="tIndex < section.calculation.expressionTokens.length - 1"> </span>
                  </template>
                </template>
                <span v-else class="placeholder">
                  暂无表达式
                </span>
              </div>
            </div>
          </div>
          
          <!-- 编辑模式 -->
          <div v-else class="edit-mode">
            <div class="calculation-editor">
              <el-form label-width="100px">
                <el-form-item label="">
                  <div class="expression-builder">
                    <!-- 操作工具栏 -->
                    <div class="expression-toolbar">
                      <div class="toolbar-buttons">
                        <!-- 运算符按钮 -->
                        <el-button 
                          v-for="op in operators" 
                          :key="op"
                          size="mini"
                          @click="addTokenToExpression(index, 'operator', op)"
                        >
                          {{ op }}
                        </el-button>
                        
                        <!-- 点位按钮 -->
                        <el-button 
                          size="mini" 
                          @click="openPointDialog(index)"
                        >
                          添加点位
                        </el-button>
                        
                        <!-- 数字按钮 -->
                        <el-button 
                          size="mini" 
                          @click="openNumberPad(index)"
                        >
                          添加数字
                        </el-button>
                        
                        <!-- 操作按钮 -->
                        <div class="action-buttons">
                          <el-button 
                            size="mini" 
                            @click="clearExpression(index)"
                          >
                            清空
                          </el-button>
                          <el-button 
                            size="mini" 
                            type="primary" 
                            @click="validateExpression(index)"
                          >
                            验证
                          </el-button>
                          <el-button 
                            size="mini" 
                            type="success" 
                            @click="saveRule(index)"
                          >
                            保存
                          </el-button>
                        </div>
                      </div>
                    </div>
                    
                    <!-- 表达式显示区域 -->
                    <div class="expression-display">
                      <div class="expression-content">
                        <template v-if="section.calculation.expressionTokens.length > 0">
                          <template v-for="(token, tIndex) in section.calculation.expressionTokens">
                            <span 
                              v-if="token.type === 'point'" 
                              :key="tIndex"
                              class="token point-link"
                              @click="showPointInfo(token.value)"
                            >
                              {{ getPointNameById(token.value) }}
                            </span>
                            <span 
                              v-else-if="token.type === 'operator'" 
                              :key="tIndex"
                              class="token operator-text"
                            >
                              {{ token.value }}
                            </span>
                            <span 
                              v-else-if="token.type === 'number'" 
                              :key="tIndex"
                              class="token number-text"
                            >
                              {{ token.value }}
                            </span>
                            <span 
                              v-else 
                              :key="tIndex"
                              class="token"
                            >
                              {{ token.value }}
                            </span>
                            <span :key="'space-'+tIndex" v-if="tIndex < section.calculation.expressionTokens.length - 1"> </span>
                          </template>
                        </template>
                        <span v-else class="placeholder">
                          点击上方按钮添加符号构建表达式
                        </span>
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 数字键盘弹窗 -->
    <el-dialog
      :visible.sync="numberPadVisible"
      width="300px"
      :before-close="closeNumberPad"
      append-to-body
    >
      <div slot="title" class="number-pad-title">
        输入数字
      </div>
      <div class="number-pad-content">
        <el-input 
          v-model="numberPadCurrentValue" 
          size="medium"
          placeholder="输入数字"
          readonly
        ></el-input>
        <div class="number-pad-keys">
          <el-button 
            v-for="num in 9" 
            :key="num"
            @click="inputNumber(num)"
            size="small"
          >
            {{ num }}
          </el-button>
          <el-button @click="inputNumber(0)" size="small">0</el-button>
          <el-button @click="inputDecimal" size="small">.</el-button>
          <el-button @click="backspace" size="small" type="warning">
            <!--<i class="el-icon-backspace"></i>-->
            <delete-two theme="outline"  fill="#333" :strokeWidth="2"/>
          </el-button>
          <el-button @click="clearNumberPad" size="small" type="danger">
            <i class="el-icon-delete"></i>
          </el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeNumberPad">取消</el-button>
        <el-button type="primary" @click="confirmNumber">确认</el-button>
      </span>
    </el-dialog>
    
    <!-- 点位选择对话框 -->
    <el-dialog
      :visible.sync="pointDialogVisible"
      width="60%"
      :before-close="closePointDialog"
      append-to-body
    >
      <div slot="title" class="point-dialog-title">
        选择点位
      </div>
      <div class="point-dialog-content">
        <el-table
          :data="points"
          highlight-current-row
          @current-change="handlePointSelection"
          height="400"
        >
          <el-table-column prop="id" label="点位ID" width="120"></el-table-column>
          <el-table-column prop="name" label="点位名称" width="200"></el-table-column>
          <el-table-column prop="instanceName" label="实例名称" width="150"></el-table-column>
          <el-table-column prop="path" label="路径"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closePointDialog">取消</el-button>
        <el-button type="primary" @click="confirmPoint" :disabled="!selectedPoint">确认</el-button>
      </span>
    </el-dialog>
    
    <!-- 点位信息对话框 -->
    <el-dialog
      :visible.sync="pointInfoDialogVisible"
      width="40%"
      append-to-body
    >
      <div slot="title" class="point-info-title">
        点位详细信息
      </div>
      <div class="point-info-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="点位ID">{{ currentPointInfo.id }}</el-descriptions-item>
          <el-descriptions-item label="点位名称">{{ currentPointInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="实例名称">{{ currentPointInfo.instanceName }}</el-descriptions-item>
          <el-descriptions-item label="路径">{{ currentPointInfo.path }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pointInfoDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {  DeleteTwo} from '@icon-park/vue'
export default {
  name: "EnergyShare",
  components: {
    DeleteTwo
  },
  data() {
    return {
      operators: ['(', ')', '+', '-', '*', '/', '^'],
      sections: [
        {
          id: 'section-1',
          name: '预热段',
          editingName: false,
          editingRule: false,
          calculation: {
            expressionTokens: [
              { type: 'point', value: 'PT1001' },
              { type: 'operator', value: '+' },
              { type: 'point', value: 'PT1002' },
              { type: 'operator', value: '*' },
              { type: 'number', value: '3' }
            ],
            currentNumber: ''
          },
          // 保存原始表达式，用于取消编辑时恢复
          originalExpressionTokens: [
            { type: 'point', value: 'PT1001' },
              { type: 'operator', value: '+' },
              { type: 'point', value: 'PT1002' },
              { type: 'operator', value: '*' },
              { type: 'number', value: '3' }
          ]
        }
      ],
      numberPadVisible: false,
      numberPadCurrentValue: '',
      numberPadTargetSectionIndex: -1,
      
      // 点位相关
      pointDialogVisible: false,
      pointDialogTargetSectionIndex: -1,
      selectedPoint: null,
      points: [
        { id: 'PT1001', name: '预热段-上部-轧侧', instanceName: '加热炉1', path: '/Furnace/Preheating/Top/MillSide' },
        { id: 'PT1002', name: '预热段-中心-轧侧', instanceName: '加热炉1', path: '/Furnace/Preheating/Center/MillSide' },
        { id: 'PT1003', name: '预热段-下部-轧侧', instanceName: '加热炉1', path: '/Furnace/Preheating/Bottom/MillSide' },
        { id: 'PT1004', name: '加热段-上部-轧侧', instanceName: '加热炉1', path: '/Furnace/Heating/Top/MillSide' },
        { id: 'PT1005', name: '加热段-中心-轧侧', instanceName: '加热炉1', path: '/Furnace/Heating/Center/MillSide' },
        { id: 'PT1006', name: '加热段-下部-轧侧', instanceName: '加热炉1', path: '/Furnace/Heating/Bottom/MillSide' },
        { id: 'PT1007', name: '均热段-上部-轧侧', instanceName: '加热炉1', path: '/Furnace/Soaking/Top/MillSide' },
        { id: 'PT1008', name: '均热段-中心-轧侧', instanceName: '加热炉1', path: '/Furnace/Soaking/Center/MillSide' },
        { id: 'PT1009', name: '均热段-下部-轧侧', instanceName: '加热炉1', path: '/Furnace/Soaking/Bottom/MillSide' }
      ],
      pointInfoDialogVisible: false,
      currentPointInfo: {}
    }
  },
  methods: {
    addSection() {
      const newSection = {
        id: `section-${Date.now()}`,
        name: '',
        editingName: false,
        editingRule: true,  // 默认进入编辑模式
        calculation: {
          expressionTokens: [],
          currentNumber: ''
        },
        originalExpressionTokens: []  // 初始为空
      }
      this.sections.push(newSection)
    },
    
    deleteSection(index) {
      this.$confirm('确定要删除该段吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.sections.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {
        // 取消删除
      })
    },
    
    editSectionName(index) {
      this.sections[index].editingName = true
    },
    
    editRule(index) {
      this.sections[index].editingRule = true
      // 进入编辑模式时，保存当前表达式作为原始表达式
      this.sections[index].originalExpressionTokens = JSON.parse(JSON.stringify(this.sections[index].calculation.expressionTokens))
    },
    
    cancelEditRule(index) {
      // 取消编辑时，恢复到原始表达式
      this.sections[index].calculation.expressionTokens = JSON.parse(JSON.stringify(this.sections[index].originalExpressionTokens))
      this.sections[index].editingRule = false
    },
    
    addTokenToExpression(sectionIndex, type, value) {
      this.sections[sectionIndex].calculation.expressionTokens.push({
        type,
        value
      })
    },
    
    openNumberPad(sectionIndex) {
      this.numberPadVisible = true;
      this.numberPadCurrentValue = '';
      this.numberPadTargetSectionIndex = sectionIndex;
    },
    
    closeNumberPad() {
      this.numberPadVisible = false;
      this.numberPadCurrentValue = '';
      this.numberPadTargetSectionIndex = -1;
    },
    
    inputNumber(num) {
      this.numberPadCurrentValue += num;
    },
    
    inputDecimal() {
      // 避免重复输入小数点
      if (this.numberPadCurrentValue.indexOf('.') === -1) {
        // 如果当前值为空，添加前导0
        if (this.numberPadCurrentValue === '') {
          this.numberPadCurrentValue = '0.';
        } else {
          this.numberPadCurrentValue += '.';
        }
      }
    },
    
    backspace() {
      this.numberPadCurrentValue = this.numberPadCurrentValue.slice(0, -1);
    },
    
    clearNumberPad() {
      this.numberPadCurrentValue = '';
    },
    
    confirmNumber() {
      const value = this.numberPadCurrentValue;
      if (value && this.isNumber(value)) {
        this.addTokenToExpression(this.numberPadTargetSectionIndex, 'number', value);
        this.closeNumberPad();
      } else if (value) {
        this.$message.error('请输入有效的数字');
      } else {
        this.closeNumberPad();
      }
    },
    
    // 点位相关方法
    openPointDialog(sectionIndex) {
      this.pointDialogVisible = true;
      this.pointDialogTargetSectionIndex = sectionIndex;
      this.selectedPoint = null;
    },
    
    closePointDialog() {
      this.pointDialogVisible = false;
      this.pointDialogTargetSectionIndex = -1;
      this.selectedPoint = null;
    },
    
    handlePointSelection(currentRow) {
      this.selectedPoint = currentRow;
    },
    
    confirmPoint() {
      if (this.selectedPoint) {
        this.addTokenToExpression(this.pointDialogTargetSectionIndex, 'point', this.selectedPoint.id);
        this.closePointDialog();
      }
    },
    
    showPointInfo(pointId) {
      const point = this.points.find(p => p.id === pointId);
      if (point) {
        this.currentPointInfo = { ...point };
        this.pointInfoDialogVisible = true;
      }
    },
    
    getPointNameById(pointId) {
      const point = this.points.find(p => p.id === pointId);
      return point ? point.name : pointId;
    },
    
    // 删除最后一个元素的方法
    handleDeleteLastToken() {
      // 找到当前处于编辑模式的段
      const editingSectionIndex = this.sections.findIndex(section => section.editingRule);
      if (editingSectionIndex !== -1 && this.sections[editingSectionIndex].calculation.expressionTokens.length > 0) {
        this.sections[editingSectionIndex].calculation.expressionTokens.pop();
      }
    },
    
    clearExpression(sectionIndex) {
      this.sections[sectionIndex].calculation.expressionTokens = []
    },
    
    getTokenTagType(tokenType) {
      switch (tokenType) {
        case 'operator':
          return 'success'  // 绿色
        case 'number':
          return 'warning'  // 黄色
        default:
          return 'info'     // 灰色
      }
    },
    
    validateExpression(sectionIndex) {
      const tokens = this.sections[sectionIndex].calculation.expressionTokens
      if (!tokens.length) {
        this.$message.warning('表达式为空')
        return
      }
      
      // 简单的表达式验证
      try {
        // 这里可以添加更复杂的表达式验证逻辑
        let expression = ''
        tokens.forEach(token => {
          if (token.type === 'point') {
            // 点位用1代替进行验证
            expression += '1'
          } else {
            expression += token.value
          }
        })
        
        // 尝试计算表达式来验证其有效性
        // 注意：这里仅为演示，实际应用中应使用更安全的表达式解析器
        // eslint-disable-next-line no-eval
        const result = eval(expression)
        if (typeof result === 'number' && !isNaN(result)) {
          this.$message.success('表达式验证通过')
        } else {
          this.$message.error('表达式验证失败')
        }
      } catch (e) {
        this.$message.error('表达式验证失败: ' + e.message)
      }
    },
    
    saveRule(sectionIndex) {
      this.$confirm('确定要保存该计算规则吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 保存时，更新原始表达式为当前表达式
        this.sections[sectionIndex].originalExpressionTokens = JSON.parse(JSON.stringify(this.sections[sectionIndex].calculation.expressionTokens))
        this.sections[sectionIndex].editingRule = false
        this.$message.success('计算规则保存成功')
      }).catch(() => {
        // 取消保存
      })
    },
    
    isNumber(value) {
      return !isNaN(parseFloat(value)) && isFinite(value)
    }
  }
}
</script>

<style scoped>
.energy-share-container {
  padding: 20px;
  height: calc(100vh - 40px);
  overflow-y: auto;
  outline: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.section-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.section-title span {
  font-weight: bold;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
}

.section-title span:hover {
  background-color: #e4e7ed;
}

.section-actions {
  display: flex;
  align-items: center;
}

.section-actions .el-button {
  margin-left: 10px;
}

.preview-mode {
  padding: 20px;
}

.expression-preview {
  display: flex;
  align-items: flex-start;
}

.preview-label {
  font-weight: bold;
  margin-right: 10px;
  white-space: nowrap;
  line-height: 32px;
}

.expression-content {
  flex: 1;
  //min-height: 32px;
  height: 60px;
  line-height: 100%;
  font-size: 20px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  padding: 5px;
  //border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

.edit-mode {
  margin: 20px;
  background-color: #d8e0ea;

}

.calculation-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.expression-builder {
  width: 100%;
}

.expression-toolbar {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.toolbar-buttons {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons {
  display: flex;
  margin-left: auto;
}

.action-buttons .el-button {
  margin-left: 10px;
}

.expression-display {
  min-height: 100px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.expression-content {
  min-height: 30px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.token {
  padding: 2px 4px;
  margin: 2px;
}

.point-link {
  color: #409eff;
  cursor: pointer;
  text-decoration: none;
}

.point-link:hover {
  color: #66b1ff;
}

.operator-text {
  color: #67c23a;
  font-weight: bold;
}

.number-text {
  color: #e6a23c;
}

.placeholder {
  color: #c0c4cc;
  font-style: italic;
}

/* 数字键盘样式 */
.number-pad-title {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.number-pad-content {
  padding: 10px 0;
}

.number-pad-keys {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin-top: 15px;
}

.number-pad-keys .el-button {
  padding: 10px;
  font-size: 16px;
}

/* 点位对话框样式 */
.point-dialog-title,
.point-info-title {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.point-dialog-content {
  padding: 10px 0;
}

.dialog-footer {
  text-align: right;
}
</style>